<?php
  $isExcl = ($message[0] == '!');
  if ($isExcl) $message = substr($message, 1);

  if (preg_match('#^s/((?:[^\\\\/]|\\\\.)*)/((?:[^\\\\/]|\\\\.)*)(?:/(\w*))?#', $message, $matches)) {
    $txt = $isExcl
      ? @$lastMessages[strtolower($source_nick)]
      :  $lastMessage;

    $matches[3] = preg_replace('/[^imsxADSUug]/', '', $matches[3]);

    $replaceLimit = strlen($matches[3]);
    $matches[3] = str_replace("g", "", $matches[3]);
    $replaceLimit = ($replaceLimit - sizeof($matches[3])) ? 1 : -1;

    $isAction = preg_match('/^(.*?\x01ACTION\s)(.*?)(\x01.*)$/s', $txt, $matches2);
    if ($isAction)
      $txt = $matches2[2];

    $newSentence=@preg_replace('/'.$matches[1].'/'.$matches[3], $matches[2], $txt, $replaceLimit);
    if ((!$newSentence) || $newSentence == $txt) // search string not found
      return;

    $messageSender = $isExcl ? $source_nick : $lastSender;
    $isImplicitlyExcl = (strtolower($messageSender) == strtolower($source_nick));

    if ($isAction) {
      $changedMessage="* $messageSender $newSentence";
      $newSentence=$matches2[1].$newSentence.$matches2[3];
    } else {
      $changedMessage = rtrim($newSentence, "\r\n");
    }

    if ($isExcl)
      $lastMessages[strtolower($sender)]=$newSentence;
    if ($isImplicitlyExcl)
      $lastMessage=$newSentence;

    if ($isExcl || $isImplicitlyExcl)
      msg("$source_nick meant: ".$changedMessage);
    else
      msg("$source_nick thinks $messageSender meant: ".$changedMessage);
  } else {
    if(!$lastMessages){ $lastMessages=Array(); }
    $lastMessages[strtolower($source_nick)]=$message;
    $lastMessage=$message;
    $lastSender=$source_nick;
  }
?>